括号匹配算法的一种正确实现(java)

本人需要判断一个字符串里括号是否成对出现,发现正则满足不了或者正则表达式太复杂,只能用java算法实现了,网上找了几段代码,发现要么不合适,要么有的情况会误判,无奈只能参考那些例子进行改造了,现在贴出来,希望对某些人有用。


import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class matchJudger
{
    // pair以右括号为key, 左括号为值
    private Map<Character, Character> pair = null;

    public matchJudger()
    {
        pair = new HashMap<Character, Character>();
        pair.put(')', '(');
        pair.put('}', '{');
        pair.put(']', '[');
    }

    public boolean isMatch(String s)
    {
        Stack<Character> sc = new Stack<Character>();
        for (int i = 0; i < s.length(); i++)
        {
            Character ch = s.charAt(i);
            if (pair.containsValue(ch))// 如果是左括号,放入栈中
            {
                sc.push(ch);
            } else if (pair.containsKey(ch)) // 如果是右括号
            {
                if (sc.empty()) // 栈为空,栈头没有字符与右括号匹配
                {
                    return false;
                }
                // 栈不为空,栈头字符与右括号匹配
                if (sc.peek() == pair.get(ch))
                {
                    sc.pop();
                } else //网上许多列子没有这里的else代码块,导致({}[]]])会被判断为true
                { // 栈不为空,栈头字符不与右括号匹配
                    return false;
                }
            }

        }

        return sc.empty() ? true : false;
    }

    public static void main(String[] args)
    {
        matchJudger judger = new matchJudger();
        System.out.println(judger.isMatch("(***)-[{-------}]")); //true
        System.out.println(judger.isMatch("(2+4)*a[5]")); //true
        System.out.println(judger.isMatch("({}[]]])")); //false
        System.out.println(judger.isMatch("())))")); //false
    }

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值